package com.lenovo.tool;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;

import javax.xml.parsers.ParserConfigurationException;

import org.w3c.dom.Document;
import org.w3c.dom.Element;
import org.xml.sax.SAXException;

/**
 * 将某个目录下的目标目录以指定文件名移动到另外一个目录下
 * @author wangdd5
 *
 */
public class TranslationMove {
	private static String sourceName;
	private static String targetName;
	
	public static void main(String[] args) {
		if (args.length != 1) {
			System.out.println("please enter the config file name");
			return;
		}

		File configFile = new File(args[0]);
		if (!configFile.exists() || !configFile.isFile()) {
			System.out.println("config file error");
			return;
		}
		
		try {
			Document doc = DocumentUtils.openDocument(configFile);
			String baseStr = doc.getElementsByTagName("basedir").item(0).getTextContent().trim();
			String outStr = doc.getElementsByTagName("outDir").item(0).getTextContent().trim();
			Element node = (Element) doc.getElementsByTagName("new_dirname").item(0);
			sourceName = node.getTextContent().trim();
			targetName = node.getAttribute("name").trim();
			File baseDir = new File(baseStr);
			File outDir = new File(outStr);
			scanFiles(baseDir, outDir);
		} catch (ParserConfigurationException e) {
			e.printStackTrace();
		} catch (SAXException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	private static void scanFiles(File src, File target) {
		File[] files = src.listFiles();
		File path;
		for (File file : files) {
			if(file.isDirectory()) {
				path = new File(target, file.getName());
				path.mkdirs();
				scanFiles(file, path);
			} else {
				String pathName = file.getParent();
				if(pathName.endsWith(sourceName)) {
					copyFile(file, target);
				}
			}
		}
	}

	private static void copyFile(File file, File target) {
		File temp = new File(target.getParentFile(), targetName);
		target.renameTo(temp);
		
		InputStream reader = null;
		OutputStream writer = null;
		try {
			reader = new FileInputStream(file);
			writer = new FileOutputStream(new File(temp, file.getName()));
			byte[] buff = new byte[1024];
			int len;
			while ((len = reader.read(buff)) != -1) {
				writer.write(buff, 0, len);
			}
		} catch (FileNotFoundException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		} finally {
			if(reader != null) {
				try {
					reader.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
			if(writer != null) {
				try {
					writer.close();
				} catch (IOException e) {
					e.printStackTrace();
				}
			}
		}
		
	}
}
